let http = require('http');
let fs = require('fs');
let path = require('path');
let mime = require('mime');

let server = http.createServer();
let staticPath = path.join(__dirname);
server.on('request',(req,res) => {
    console.log(req.url);
    let url = req.url;
    let reqPath = path.join(staticPath,url);
    console.log(reqPath);
    res.setHeader('Content-type',mime.getType(url));
    if(url == '/' || url == '/index') {
        readFun('index.html',res);
    }else if(url == '/register') {
        readFun('/register.html',res);
    }else if(url == '/home') {
        readFun('/home.html',res);
    }else if(url == '/login') {
        readFun('/login.html',res);
    }else {
        // readFun('/404.html',res);
        fs.readFile(reqPath,(err,data) => {
            if(err) {
                res.setHeader('Content-type','text/html;charset=utf-8');
                return res.end('<h1>404</h1>')
            }
            res.end(data);
        })
    }
    
})

const readFun = (fileName,response) => {
    fs.readFile(path.join(__dirname,fileName),(err,data) => {
        if(err) return console.log(err);
        response.end(data);
    })
}

server.listen(8002,() => {
    console.log('服务器运行在8002端口上');
})